// 加载省市区数据
const addressData = require('china-area-data/v3/data');
Vue.component('select-district', {
    props: {
        initValue: {
            type: Array,
            default: () => ([])
        }
    },
    data(){
        return {
            provinces: addressData[86], // 省列表
            cities: {}, // 城市列表
            districts: {}, //  地区列表
            provinceId: '', // 当前选中的省
            cityId: '', // 当前选中的城市
            districtId: '', // 当前选中的地区
        };
    },
    watch: {
        provinceId(newVal){
            if (!newVal){
                this.cities = {};
                this.cityId = '';
                return;
            }

            // 当前城市列表设为当前省下城市
            this.cities = addressData[newVal];

            // 如果当前选中的城市不在当前省下，则将选中城市清空
            if (!this.cities[this.cityId]){
                this.cityId = '';
            }
        },
        cityId(newVal){
            if (!newVal){
                this.districts = {};
                this.districtId = '';
                return;
            }

            this.districts = addressData[newVal];
            if (!this.districts[this.districtId]){
                this.districtId = '';
            }
        },
        districtId(){
            this.$emit('change', [this.provinces[this.provinceId], this.cities[this.cityId], this.districts[this.districtId]]);
        }
    },
    created(){console.log(this.initValue);
        this.setFormValue(this.initValue);
    },
    methods: {
        setFormValue(value){
            value = _.filter(value);
            if (value.length == 0){
                return this.provinceId = '';
            }

            // 省
            let provinceId = _.findKey(this.provinces, o => o === value[0]);
            if (!provinceId){
                return this.provinceId = '';
            }
            this.provinceId = provinceId;

            // 市
            let cityId = _.findKey(addressData[provinceId], o => o === value[1]);
            if (!cityId){
                return this.cityId = '';
            }
            this.cityId = cityId;

            // 区
            let districtId = _.findKey(addressData[cityId], o => o === value[2]);
            if (!districtId){
                return this.districtId = '';
            }
            this.districtId = districtId;
        }
    }
});
